package com.atguigu.demojuc.chap02;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//资源类
class MyCache {
    //缓存
    Map<String, String> cache = new HashMap<>();
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    //写缓存
    public void put(String key, String value) {
        try {
            lock.writeLock().lock();
            System.out.println(Thread.currentThread().getName() + "\t" + "存储：key=" + key + ", value=" + value);
            cache.put(key, value);
            System.out.println(Thread.currentThread().getName() + "\t" + "存储完成");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }
    //读缓存
    public String get(String key) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t" + "---come in,获取key=" + key);
            System.out.println(Thread.currentThread().getName() + "\t" + "读取的值value=" + cache.get(key));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }

        return cache.get(key);
    }
}

/**
 * 演示读写锁的使用：ReentrantReadWriteLock
 *
 *  特点：
 *      1.写写 不可并发
 *      2.读写、写读 不可并发
 *      3.读读 可并发
 */

public class ReentrantReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 1; i <= 5; i++) {
            String key = Integer.toString(i);
            String value  = String.valueOf(i);
            new Thread(() -> {
                myCache.put(key,value);
            }, "W-"+i).start();
        }
        for (int i = 1; i <= 5; i++) {
            String key = Integer.toString(i);
            new Thread(() -> {
                myCache.get(key);
            }, "R-"+i).start();
        }
    }
}
